Skip to contentMethod: CollectionInstanceContext(Collection, Class, Map)
1: /**
2: * Copyright (C) 2017 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jsonld.deserialization;
16:
17: import cz.cvut.kbss.jsonld.deserialization.util.DataTypeTransformer;
18: import cz.cvut.kbss.jsonld.exception.JsonLdDeserializationException;
19:
20: import java.util.Collection;
21: import java.util.Map;
22:
23: class CollectionInstanceContext<T extends Collection> extends InstanceContext<T> {
24:
25: private final Class<?> targetType;
26:
27: CollectionInstanceContext(T instance, Map<String, Object> knownInstances) {
28: super(instance, knownInstances);
29: this.targetType = null;
30: }
31:
32: CollectionInstanceContext(T instance, Class<?> targetType, Map<String, Object> knownInstances) {
33: super(instance, knownInstances);
34: this.targetType = targetType;
35: }
36:
37: /**
38: * Adds the specified item into this collection.
39: *
40: * @param item The item to add
41: */
42: @Override
43: void addItem(Object item) {
44: if (targetType == null) {
45: instance.add(item);
46: return;
47: }
48: Object toAdd = item;
49: if (!targetType.isAssignableFrom(item.getClass())) {
50: if (knownInstances.containsKey(item.toString())) {
51: toAdd = knownInstances.get(item.toString());
52: if (!targetType.isAssignableFrom(toAdd.getClass())) {
53: toAdd = null;
54: }
55: } else {
56: toAdd = DataTypeTransformer.transformValue(item, targetType);
57: }
58: }
59: if (toAdd == null) {
60: throw typeMismatch(targetType, item.getClass());
61: }
62: instance.add(toAdd);
63: }
64:
65: private JsonLdDeserializationException typeMismatch(Class<?> expected, Class<?> actual) {
66: return new JsonLdDeserializationException(
67: "Type mismatch. Unable to transform instance of type " + actual + " to the expected type " + expected);
68: }
69:
70: @Override
71: Class<?> getItemType() {
72: return targetType;
73: }
74: }